package net.ojbk.saishi.action;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.http.Part;

import net.ojbk.saishi.po.syMatch;
import net.ojbk.saishi.service.MatchBackService;
import net.ojbk.saishi.service.sponsorService;
import net.ojbk.util.FileTool;
import net.ojbk.util.WebPathTool;


/**
 * Servlet implementation class LaunchEventServlet
 */
@WebServlet("/LaunchEventServlet")
@MultipartConfig(
        maxFileSize = 100*1024*1024,
        maxRequestSize = 130*1024*1024
)  
public class LaunchEventServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
    /**
     * @see HttpServlet#HttpServlet()
     */
    public LaunchEventServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		response.getWriter().append("Served at: ").append(request.getContextPath());
	}

	/**
	 * 处理赛事发布
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		response.setContentType("text/html; charset=UTF-8");
		PrintWriter out = response.getWriter();
		HttpSession session=request.getSession();
		if (!(session != null && session.getAttribute("login") != null && (boolean)session.getAttribute("login"))) { // 如果未登录
			String message = "<a href=\"./"
					+ FileTool.getFileName(request.getHeader("Referer"))
					+ "\">&nbsp;&nbsp;&nbsp;Return</a>";
			out.write("not login. <br/>" + message);
			System.out.println(FileTool.getFileName(request.getHeader("Referer")));
			return ;
		}
		
		// 获取 用户ID
	    String userId=(String)session.getAttribute("myId");
	    // 生成 唯一的matchId
	    String matchId = MatchBackService.getOnlyMatchId(); // 唯一的 MatchId
        // 构造 service 层参数
	    syMatch sym=new syMatch();
        // 配置上传参数 --------------- 开始接收 post 数据
	    // 1、sym 将传入 赛事标题\赛事介绍\赛事密码\结束时间\文件名格\是否需要材料\serId 
		sym.setTitle(request.getParameter("title"));
		sym.setContent(request.getParameter("content"));
		sym.setPw(request.getParameter("pw"));
		sym.setFileFormat(request.getParameter("fileFormat"));
		// 获取结束时间
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
		Date date = null;
		try {
			date = format.parse(request.getParameter("endTime").replaceAll("T", " "));
		} catch (ParseException e) {
			Calendar calendar = new GregorianCalendar();
			calendar.setTime(new Date());
			calendar.add(Calendar.DATE, 7);
			date = calendar.getTime();
		}
	    sym.setEndTime(date);
	    // ↑ 获取结束  时间
	    sym.setUserId(userId);
	    sym.setMatchId(matchId);
	    sym.setNeedFile(Boolean.valueOf(request.getParameter("needFile")));
	    // 存储 海报 
	    // 赛事文件夹
	    String uploadPath = WebPathTool.getMatchDataPath() + userId + File.separator + matchId + File.separator;
	    File tempFile = new File(uploadPath);
	    if (!tempFile.exists()) {
	    	tempFile.setWritable(true, false);
	    }
	    // 构造完文件夹
	    
	    
	    File uploadPathFile = tempFile; // 海报 上次的
	    if (!uploadPathFile.exists()) { // 不存在
	    	uploadPathFile.mkdirs();
	    }
        
        Part part1 = request.getPart("poster");
        File file1 = new File(uploadPathFile.getPath() + File.separator + "poster" + FileTool.getFileType(part1.getSubmittedFileName()));
        // file1 为文件
        part1.write(file1.getPath()); // 写出

	    // 建立赛事
        String[] basicInfo = request.getParameterValues("basicInfo");
        String[] extraInfo = request.getParameterValues("extraInfo");
        if (basicInfo == null) basicInfo = new String[0];
        if (extraInfo == null) extraInfo = new String[0];
	    sponsorService.holdMatch(sym, basicInfo, extraInfo, matchId);
	    //  重定向到 赛事介绍页面
		response.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY);
		response.setHeader("Location", "./saishi.jsp?matchId=" + matchId);
	}

}
